package ad

import (
	"fmt"
	"time"

	"gddgame.cc/galaxy/common/dsl/game"
)

const providerName = "ad"
const GiftAdGapConfig = "GiftAdGap"
const AdBrandListConfig = "AdBrandList"

func init() {
	_ = game.RegisterGlobalModule(game.ModuleProvider{
		Name:    providerName,
		Depends: []string{"config"},

		OnInit: func(env *game.Environment) error {
			return nil
		},
	})
}

func NextAd(env *game.Environment, openId string, plane AdPlane) (*AdInfo, error) {
	var AdBrandList []string
	if err := env.Config(AdBrandListConfig, &AdBrandList); err != nil {
		return nil, err
	}
	var info AdInfo
	if err := env.Get(fmt.Sprintf("ad-%d:%s", plane, openId), &info); err != nil {
		return &AdInfo{
			Plane: plane,
			Brand: AdBrandList[0],
		}, nil
	}
	// 切换为下一次的brand
	index := 0
	for key, value := range AdBrandList {
		if value == info.Brand {
			index = key + 1
			if index >= len(AdBrandList) {
				index = 0
			}
			break
		}
	}
	info.Brand = AdBrandList[index]
	return &info, nil
}

func ResponseAd(env *game.Environment, openId string, adInfo *AdInfo) error {
	return env.SetExpire(fmt.Sprintf("ad-%d:%s", adInfo.Plane, openId), &AdInfo{
		Plane:    adInfo.Plane,
		Brand:    adInfo.Brand,
		Response: true,
	}, 86400)
}
func UpdateAd(env *game.Environment, openId string, adInfo *AdInfo) error {
	return env.SetExpire(fmt.Sprintf("ad-%d:%s", adInfo.Plane, openId), &AdInfo{
		Plane: adInfo.Plane,
		Brand: adInfo.Brand,
	}, 86400)
}

func NextAdTime(env *game.Environment, openId string, plane AdPlane) (*AdTimeInfo, error) {
	var AdBrandList []string
	if err := env.Config(AdBrandListConfig, &AdBrandList); err != nil {
		return nil, err
	}
	var info AdTimeInfo
	if err := env.Get(fmt.Sprintf("ad-%d:%s", plane, openId), &info); err != nil {
		return &AdTimeInfo{
			Plane: plane,
			Brand: AdBrandList[0],
			Next:  time.Now().Unix(),
		}, nil
	}
	// 切换为下一次的brand
	index := 0
	for key, value := range AdBrandList {
		if value == info.Brand {
			index = key + 1
			if index >= len(AdBrandList) {
				index = 0
			}
			break
		}
	}
	info.Brand = AdBrandList[index]
	return &info, nil
}
func ResponseAdTime(env *game.Environment, openId string, adInfo *AdTimeInfo) error {
	return env.SetExpire(fmt.Sprintf("ad-%d:%s", adInfo.Plane, openId), &AdTimeInfo{
		Plane:    adInfo.Plane,
		Brand:    adInfo.Brand,
		Response: true,
		Next:     adInfo.Next,
	}, 86400)
}
func UpdateAdTime(env *game.Environment, openId string, adInfo *AdTimeInfo) error {
	ti := time.Now().Unix()

	var GiftAdGap int
	if err := env.Config(GiftAdGapConfig, &GiftAdGap); err != nil {
		return err
	}
	return env.SetExpire(fmt.Sprintf("ad-%d:%s", adInfo.Plane, openId), &AdTimeInfo{
		Plane: adInfo.Plane,
		Brand: adInfo.Brand,
		Next:  ti + int64(GiftAdGap), // todo 变动调整下次广告时间
	}, 86400)
}
